package com.zrwl.poscloud.xo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrwl.poscloud.base.entity.AdminLog;
//import com.zrwl.poscloud.base.entity.AdminLogConfig;
import com.zrwl.poscloud.base.entity.AdminLogConfig;
import com.zrwl.poscloud.base.enums.EBusiType;
import com.zrwl.poscloud.base.enums.EStatus;
import com.zrwl.poscloud.base.superI.SuperServiceImpl;
import com.zrwl.poscloud.commons.utils.DateUtils;
import com.zrwl.poscloud.commons.utils.ResultUtil;
import com.zrwl.poscloud.commons.utils.StringUtils;
import com.zrwl.poscloud.xo.global.MessageConf;
import com.zrwl.poscloud.xo.global.SQLConf;
import com.zrwl.poscloud.xo.global.SysConf;
import com.zrwl.poscloud.xo.mapper.AdminLogMapper;
//import com.zrwl.poscloud.xo.mapper.AgentChargeHandleMapper;
//import com.zrwl.poscloud.xo.mapper.RechargeTradeSettleMapper;
//import com.zrwl.poscloud.xo.service.AdminLogConfigService;
import com.zrwl.poscloud.xo.service.AdminLogConfigService;
import com.zrwl.poscloud.xo.service.AdminLogService;
import com.zrwl.poscloud.xo.service.AdminService;
//import com.zrwl.poscloud.xo.service.DeptAdminRService;
//import com.zrwl.poscloud.xo.vo.AdminLogConfigVO;
import com.zrwl.poscloud.xo.vo.AdminLogConfigVO;
import com.zrwl.poscloud.xo.vo.AdminLogVO;
import com.zrwl.poscloud.xo.vo.AdminVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 操作员日志 服务实现类
 *
 * @author 刘思童 AutoGenerate
 * @date 2021-11-23
 */
@Service
public class AdminLogServiceImpl extends SuperServiceImpl<AdminLogMapper, AdminLog> implements AdminLogService {

    @Autowired
    private AdminLogService adminLogService;
    @Autowired
    private AdminService adminService;
    @Resource
    private AdminLogMapper adminLogMapper;
    @Autowired
    private AdminLogConfigService adminLogConfigService;
//    @Autowired
//    private DeptAdminRService deptAdminRService;
//    @Resource
//    private RechargeTradeSettleMapper rechargeTradeSettleMapper;
//    @Resource
//    private AgentChargeHandleMapper agentChargeHandleMapper;

    @Override
    public IPage<AdminLogVO> getPageListForCancelBusiness(AdminLogVO adminLogVO) {
        Page<AdminLogVO> page = new Page<>();
        page.setCurrent(adminLogVO.getCurrentPage());
        page.setSize(adminLogVO.getPageSize());

        QueryWrapper<AdminLogVO> wrapper = new QueryWrapper<>();
        wrapper.eq("business_type", "4");

        IPage<AdminLogVO> pageList = adminLogMapper.getPageListForCancelBusiness(wrapper, page, adminLogVO);
        List<AdminLogVO> list = pageList.getRecords();
        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public IPage<AdminLogVO> getPageList(AdminLogVO adminLogVO) {
        Page<AdminLogVO> page = new Page<>();
        page.setCurrent(adminLogVO.getCurrentPage());
        page.setSize(adminLogVO.getPageSize());
        IPage<AdminLogVO> pageList = adminLogMapper.getPageList(page, adminLogVO);

        List<AdminLogVO> list = pageList.getRecords();
        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public AdminLog getLogBySource(int sourceType, String sourceUid) {
        QueryWrapper<AdminLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("source_type", sourceType);
        queryWrapper.eq("source_uid", sourceUid);
        AdminLog entity = adminLogService.getOne(queryWrapper);
        return entity;
    }

    @Override
    public List<AdminLog> getAllList(AdminLogVO adminLogVO) {
        QueryWrapper<AdminLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        queryWrapper.orderByAsc(SQLConf.CREATE_TIME);
        List<AdminLog> list = adminLogService.list(queryWrapper);
        return list;
    }

    @Override
    public String add(AdminLogVO adminLogVO) {
        AdminLog entity = new AdminLog();
        BeanUtils.copyProperties(adminLogVO, entity, SysConf.STATUS);
        entity.insert();
        adminLogVO.setUid(entity.getUid());
        return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS);
    }

    @Override
    public String edit(AdminLogVO adminLogVO) {
        AdminLog entity = adminLogService.getById(adminLogVO.getUid());
        BeanUtils.copyProperties(adminLogVO, entity);
        //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public String delete(AdminLogVO adminLogVO) {
        AdminLog entity = adminLogService.getById(adminLogVO.getUid());
        entity.setStatus(EStatus.DISABLED);
        //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public void log(AdminLogVO adminLogVO) throws RuntimeException {
        AdminLog entity = new AdminLog();
        if (StringUtils.isEmpty(adminLogVO.getAdminUid()) || StringUtils.isEmpty(adminLogVO.getAdminUid().trim()) || StringUtils.isEmpty(adminLogVO.getName())
                || StringUtils.isEmpty(adminLogVO.getName().trim())) {
            AdminVO adminVO = adminService.getMe();
            adminLogVO.setAdminUid(adminVO.getUid());
            adminLogVO.setName(adminVO.getNickName());
        }
        if (StringUtils.isEmpty(adminLogVO.getConfigUid()) || StringUtils.isEmpty(adminLogVO.getConfigUid().trim())) {
            AdminLogConfigVO adminLogConfigVO = new AdminLogConfigVO();
            adminLogConfigVO.setPageSize(100l);
            adminLogConfigVO.setCurrentPage(1l);
            adminLogConfigVO.setLogLevel(adminLogVO.getLogLevel());
            adminLogConfigVO.setBusinessType(adminLogVO.getBusinessType());
            adminLogConfigVO.setOperationType(adminLogVO.getOperationType());
            List<AdminLogConfig> records = adminLogConfigService.getPageList(adminLogConfigVO).getRecords();
            if (records.size() > 0) {
                adminLogVO.setConfigUid(records.get(0).getUid());
            }
        }
        BeanUtils.copyProperties(adminLogVO, entity, SysConf.STATUS);
        entity.insert();
    }
    @Override
    public Map<String, Object> getPageEntryInfo() {
        //日总计(包含收入,支出,现金，其他缴费,充值机,卡片,补贴)
        Map<String, Object> day = getDayEntryInfo(null,null,true);
        //月总计(包含收入,支出)
        Map<String, Object> monthly = getMonthly();
        Map<String, Object> result = new HashMap<>();
        result.put("day", day);
        result.put("monthly", monthly);
        return result;
    }
    /**
     * 获取现金相关信息
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param adminVO
     * @return
     */
    private Map<String, Object> getCashRelatedInfo(String startTime, String endTime, AdminVO adminVO) {
        return adminLogMapper.getCashRelatedInfo(adminVO.getUid(), startTime, endTime);
    }

    /**
     * 获取卡片相关信息
     *
     * @param startTime
     * @param endTime
     * @param adminVO
     * @return
     */
    private Map<String, Object> getCardRelatedInfo(String startTime, String endTime, AdminVO adminVO) {
        List<Map<String, Object>> cardRelatedInfo = adminLogMapper.getCardRelatedInfo(adminVO.getUid(), startTime, endTime);
        Map<String, Object> result = new HashMap<>();
        result.put("cardTariff", adminLogMapper.getCardTariff(adminVO.getUid(), startTime, endTime));
        for (Map<String, Object> map : cardRelatedInfo) {
            Map<String,Object> entity = new HashMap<>();
            entity.put("cardCount",map.get("cardCount"));
            entity.put("totalNumber",map.get("totalNumber"));
            switch (Objects.requireNonNull(EBusiType.getByValue(Integer.parseInt(String.valueOf(map.get("business_type")))))){
                case icCardOpen: result.put("cardOpen",entity);break;
                case icCardChange: result.put("cardChange",entity);break;
                case icCardCheckOut: result.put("cardCheckOut",entity);break;
            }

        }
        return result;
    }

    /**
     * 获取下发补贴相关信息
     *
     * @param startTime
     * @param endTime
     * @param adminVO
     * @return
     */
    private Map<String, Object> getSubsidyRelatedInfo(String startTime, String endTime, AdminVO adminVO) {
        Map<String, Object> result = new HashMap<>();
        result.put("subsidyAmt", adminLogMapper.getSubsidyRelatedInfo(adminVO.getUid(), startTime, endTime));
        return result;
    }

    /**
     * 获取代理相关信息
     *
     * @param startTime
     * @param endTime
     * @param adminVO
     * @return
     */
//    private Map<String, Object> getAgentRelatedInfo(String startTime, String endTime, AdminVO adminVO) {
//        String[] deptRoleTree = deptAdminRService.getMyDeptRoleTreeCode(adminVO.getCompanyUid(), adminVO.getUid());
//        return adminLogMapper.getAgentRelatedInfo(deptRoleTree, startTime, endTime);
//    }

    /**
     * 获取充值相关信息
     *
     * @param startTime
     * @param endTime
     * @param adminVO
     * @return
     */
//    private Map<String, Object> getRechargeRelatedInfo(String startTime, String endTime, AdminVO adminVO) {
//        return adminLogMapper.getRechargeRelatedInfo(adminVO.getCompanyUid(), startTime, endTime);
//    }

    /**
     * 月总计(包含收入,支出)
     *
     * @return
     */
    private Map<String, Object> getMonthly() {
        AdminVO adminVO = adminService.getMe();
        double[] thisArray = new double[DateUtils.getCurrentMonthDay()];
        for (int i = 1; i <= DateUtils.getCurrentMonthDay(); i++) {
            String month = DateUtils.getMonthStartTimeStr().split(" ")[0].substring(0,7);
            String day = i>10?String.valueOf(i):"0"+ i;
            String startTime = month+"-"+day+" 00:00:00";
            String endTime = month+"-"+day+" 23:59:59";
            double totalInAmt = 0.0;
            Map<String, Object> dayEntryInfo = getDayEntryInfo(startTime, endTime, false);
            if(dayEntryInfo.get("totalInAmt") != null){
                totalInAmt = Double.parseDouble(String.valueOf(dayEntryInfo.get("totalInAmt")));
            }
            thisArray[i-1] = totalInAmt;

        }
        Map<String, Object> thisMonthly = getMonthlyEntryInfo(DateUtils.getMonthStartTimeStr(), DateUtils.getMonthEndTimeStr(), adminVO);
        Map<String, Object> lastMonthly = getMonthlyEntryInfo(DateUtils.getLastMonthStartTimeStr(), DateUtils.getLastMonthEndTimeStr(), adminVO);
        Map<String, Object> result = new HashMap<>();
        result.put("thisArray",thisArray);
        result.put("thisMonthly", thisMonthly);
        result.put("lastMonthly", lastMonthly);
        return result;
    }

    /**
     * 月条目信息
     *
     * @param startTime
     * @param endTime
     * @param adminVO
     * @return
     */
    private Map<String, Object> getMonthlyEntryInfo(String startTime, String endTime, AdminVO adminVO) {
        //现金相关信息
        Map<String, Object> cashRelatedInfo = getCashRelatedInfo(startTime, endTime, adminVO);
        //卡片相关信息
        Map<String, Object> cardRelatedInfo = getCardRelatedInfo(startTime, endTime, adminVO);
//        //代理相关信息
//        Map<String, Object> agentRelatedInfo = getAgentRelatedInfo(startTime, endTime, adminVO);
//        //充值机相关信息
//        Map<String, Object> rechargeRelatedInfo = getRechargeRelatedInfo(startTime, endTime, adminVO);
        //下发补贴相关信息
        Map<String, Object> subsidyRelatedInfo = getSubsidyRelatedInfo(startTime, endTime, adminVO);
        double cashInAmt = 0.0, cashOutAmt = 0.0,
                cardTariff = 0.0, agentInAmt = 0.0, agentOutAmt = 0.0,
                rechargeInAmt = 0.0, rechargeOutAmt = 0.0, subsidyAmt = 0.0;
        if (cashRelatedInfo != null && cashRelatedInfo.get("cashInAmt") != null) {
            cashInAmt = Double.parseDouble(String.valueOf(cashRelatedInfo.get("cashInAmt")));
        }
        if (cashRelatedInfo != null && cashRelatedInfo.get("cashOutAmt") != null) {
            cashOutAmt = Double.parseDouble(String.valueOf(cashRelatedInfo.get("cashOutAmt")));
        }
//        if (agentRelatedInfo != null && agentRelatedInfo.get("agentInAmt") != null) {
//            agentInAmt = Double.parseDouble(String.valueOf(agentRelatedInfo.get("agentInAmt")));
//        }
//        if (agentRelatedInfo != null && agentRelatedInfo.get("agentOutAmt") != null) {
//            agentOutAmt = Double.parseDouble(String.valueOf(agentRelatedInfo.get("agentOutAmt")));
//        }
//        if (rechargeRelatedInfo != null && rechargeRelatedInfo.get("rechargeInAmt") != null) {
//            rechargeInAmt = Double.parseDouble(String.valueOf(rechargeRelatedInfo.get("rechargeInAmt")));
//        }
//        if (rechargeRelatedInfo != null && rechargeRelatedInfo.get("rechargeOutAmt") != null) {
//            rechargeOutAmt = Double.parseDouble(String.valueOf(rechargeRelatedInfo.get("rechargeOutAmt")));
//        }
        if (cardRelatedInfo != null && cardRelatedInfo.get("cardTariff") != null) {
            cardTariff = Double.parseDouble(String.valueOf(cardRelatedInfo.get("cardTariff")));
        }
        if (subsidyRelatedInfo != null && subsidyRelatedInfo.get("subsidyAmt") != null) {
            subsidyAmt = Double.parseDouble(String.valueOf(subsidyRelatedInfo.get("subsidyAmt")));
        }
        double totalInAmt = cashInAmt + agentInAmt + rechargeInAmt + cardTariff;
        double totalOutAmt = cashOutAmt + agentOutAmt + rechargeOutAmt + subsidyAmt;
        Map<String, Object> result = new HashMap<>();
        result.put("totalInAmt", totalInAmt);
        result.put("totalOutAmt", totalOutAmt);
        return result;
    }

    /**
     * 日条目信息
     * @param startTime
     * @param endTime
     * @param isDetail
     * @return
     */
    private Map<String, Object> getDayEntryInfo(String startTime,String endTime,boolean isDetail) {
        startTime = startTime == null?DateUtils.getToDayStartTime():startTime; //今天开始时间
        endTime = endTime==null?DateUtils.getToDayEndTime():endTime; //今天结束时间
        AdminVO adminVO = adminService.getMe();
        //现金相关信息
        Map<String, Object> cashRelatedInfo = getCashRelatedInfo(startTime, endTime, adminVO);
        //卡片相关信息
        Map<String, Object> cardRelatedInfo = getCardRelatedInfo(startTime, endTime, adminVO);
        //下发补贴相关信息
        Map<String, Object> subsidyRelatedInfo = getSubsidyRelatedInfo(startTime, endTime, adminVO);
        //代理相关信息
//        Map<String, Object> agentRelatedInfo = getAgentRelatedInfo(startTime, endTime, adminVO);
//        //充值机相关信息
//        Map<String, Object> rechargeRelatedInfo = getRechargeRelatedInfo(startTime, endTime, adminVO);
        double cashInAmt = 0.0, cashOutAmt = 0.0,
                cardTariff = 0.0, agentInAmt = 0.0, agentOutAmt = 0.0,
                rechargeInAmt = 0.0, rechargeOutAmt = 0.0, subsidyAmt = 0.0;
        int totalCardCount = 0;
        if (cashRelatedInfo != null && cashRelatedInfo.get("cashInAmt") != null) {
            cashInAmt = Double.parseDouble(String.valueOf(cashRelatedInfo.get("cashInAmt")));
        }
        if (cashRelatedInfo != null && cashRelatedInfo.get("cashOutAmt") != null) {
            cashOutAmt = Double.parseDouble(String.valueOf(cashRelatedInfo.get("cashOutAmt")));
        }
//        if (agentRelatedInfo != null && agentRelatedInfo.get("agentInAmt") != null) {
//            agentInAmt = Double.parseDouble(String.valueOf(agentRelatedInfo.get("agentInAmt")));
//        }
//        if (agentRelatedInfo != null && agentRelatedInfo.get("agentOutAmt") != null) {
//            agentOutAmt = Double.parseDouble(String.valueOf(agentRelatedInfo.get("agentOutAmt")));
//        }
//        if (rechargeRelatedInfo != null && rechargeRelatedInfo.get("rechargeInAmt") != null) {
//            rechargeInAmt = Double.parseDouble(String.valueOf(rechargeRelatedInfo.get("rechargeInAmt")));
//        }
//        if (rechargeRelatedInfo != null && rechargeRelatedInfo.get("rechargeOutAmt") != null) {
//            rechargeOutAmt = Double.parseDouble(String.valueOf(rechargeRelatedInfo.get("rechargeOutAmt")));
//        }
        if (cardRelatedInfo != null && cardRelatedInfo.get("cardTariff") != null) {
            cardTariff = Double.parseDouble(String.valueOf(cardRelatedInfo.get("cardTariff")));
        }
        if (cardRelatedInfo != null && cardRelatedInfo.get(String.valueOf(EBusiType.icCardOpen.getType())) != null) {
            totalCardCount = totalCardCount + Integer.parseInt(String.valueOf(cardRelatedInfo.get(String.valueOf(EBusiType.icCardOpen.getType()))));
        }
        if (cardRelatedInfo != null && cardRelatedInfo.get(String.valueOf(EBusiType.icCardChange.getType())) != null) {
            totalCardCount = totalCardCount + Integer.parseInt(String.valueOf(cardRelatedInfo.get(String.valueOf(EBusiType.icCardChange.getType()))));
        }
        if (subsidyRelatedInfo != null && subsidyRelatedInfo.get("subsidyAmt") != null) {
            subsidyAmt = Double.parseDouble(String.valueOf(subsidyRelatedInfo.get("subsidyAmt")));
        }
        double totalInAmt = cashInAmt + agentInAmt + rechargeInAmt + cardTariff;
        double totalOutAmt = cashOutAmt + agentOutAmt + rechargeOutAmt + subsidyAmt;
        Map<String, Object> result = new HashMap<>();
        result.put("cashIn", cashInAmt);
        result.put("totalInAmt", totalInAmt);
        result.put("totalOutAmt", totalOutAmt);
        result.put("totalCardCount", totalCardCount);
        if (isDetail) {
            result.put("cash", cashRelatedInfo);
            result.put("card", cardRelatedInfo);
            result.put("subsidy", subsidyRelatedInfo);
//            result.put("agent", agentRelatedInfo);
//            result.put("recharge", rechargeRelatedInfo);
        }
        return result;
    }
}
